'use strict';

/**
 * Created by twer on 15/3/29.
 */
angular.module('personaldocument').controller('PersonalDocumentCtrl', [
    '$scope',
    '$rootScope',
    '$routeParams',
    'FileService',
    'ImageTypes',
    'ProfilePhotoService',
    'ProfileInfoService',
    function ($scope, $rootScope, $routeParams, FileService, ImageTypes, ProfilePhotoService, ProfileInfoService) {
        $rootScope.visitedUserId = $routeParams.userId;
        var visitedUserId = $routeParams.userId;

        /**
         * 上传照片
         */
        $scope.uploadStart = function () {
            var personalProfileValue = angular.element('#personal_profile').val();
            if (!personalProfileValue) {
                alert('请选择照片！');
                return;
            }
            var currentFileType = personalProfileValue.substring(personalProfileValue.lastIndexOf('.') + 1);
            if ($.inArray(currentFileType, ImageTypes) == -1) {
                alert('照片类型不正确！');
                return;
            }

            /**
             * 上传照片
             */
            FileService.upload(angular.element('#personal_upload_loading'), 'personal_profile', function (photoId) {
                alert('照片上传成功！');
                ProfilePhotoService.edit({userId: visitedUserId}, {photoId: photoId});// 上传完后保存id
                $scope.$broadcast('ProfilePhotoUploadedEvent', photoId);
            });
        };

        /**
         * 查询基本信息
         */
        $scope.queryInfo = function () {
            ProfileInfoService.query({userId: visitedUserId}, function (response) {
                $scope.profile = response.profile;
            });
        };

        /**
         * 编辑
         */
        $scope.needEdit = function () {
            $scope.oldProfile = {};
            for (var p in $scope.profile) {
                $scope.oldProfile[p] = $scope.profile[p];
            }
            $scope.profile.editable = true;
        };

        /**
         * 放弃
         */
        $scope.discard = function () {
            $scope.profile = $scope.oldProfile;
            $scope.profile.editable = false;
        };

        /**
         * 保存
         */
        $scope.saveProfile = function() {
            $scope.profile.identity = visitedUserId;
            ProfileInfoService.edit({userId: visitedUserId}, $scope.profile, function() {
                $scope.queryInfo();
            });
        };

        $scope.queryInfo();

    }]);
